package com.example.file.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.file.entity.FileInfo;
import com.example.file.mapper.FileInfoMapper;
import com.example.file.service.IFileInfoService;
import com.example.photoalbum.entity.Photoalbum;
import com.example.util.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

/**
 * @author Jiamingzhen
 * @Date 2021/4/26 13:59
 * @ClassName FileServiceImpl
 * @Introduce
 */
@Service
public class FileInfoInfoServiceImpl extends ServiceImpl<FileInfoMapper, FileInfo> implements IFileInfoService {
    @Autowired
    private FileInfoMapper fileInfoMapper;

    @Override
    public PageResult<FileInfo> listPage(int pageNum, int pageSize, FileInfo fileInfo) {
        Page<FileInfo> page = new Page<FileInfo>(pageNum, pageSize);
        QueryWrapper<FileInfo> ew = new QueryWrapper<FileInfo>();
        if(StringUtils.isNotBlank(fileInfo.getFileName())){
            ew.like("file_name",fileInfo.getFileName());
        }
        if(StringUtils.isNotBlank(fileInfo.getFileDesc())){
            ew.like("file_desc",fileInfo.getFileDesc());
        }
        IPage iPage = fileInfoMapper.selectPage(page,ew);
        return new PageResult<FileInfo>(iPage.getRecords(), iPage.getTotal());
    }

    @Override
    public List<FileInfo> selectList(FileInfo fileInfo) {
        QueryWrapper<FileInfo> ew = new QueryWrapper<FileInfo>();
        return fileInfoMapper.selectList(ew);
    }

    @Override
    public Boolean logicDelete(FileInfo fileInfo) {
        fileInfo.setIsDel(1);
        return this.updateById(fileInfo);
    }

    @Override
    public boolean updateFilename(String fileId, String newName) {
        FileInfo fileInfo = fileInfoMapper.selectById(fileId);
        File file = new File(fileInfo.getFilePath()+fileInfo.getFileName());
        if(!file.exists()){
            return false;
        }
        File newFile = new File(fileInfo.getFilePath() + newName +fileInfo.getFileSuffix());
        fileInfo.setFileName(newFile.getName());
        if(file.renameTo(newFile)){
            fileInfoMapper.updateById(fileInfo);
            return true;
        }
        return false;
    }
}
